package com.mt4.trade.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Service;

import com.mt4.trade.config.TradeConfig;
import com.mt4.trade.dto.OrderDto;
import com.mt4.trade.service.TradeService;
import com.mt4.trade.utils.TradeUtils;

/**
 * 交易服务
 * 
 * @author ivan
 * 
 */
@Service
public class TradeServiceImpl implements TradeService {

	private static boolean IS_DUIDU = true;

	// 用户数据池
	public static Map<String, Map<String, Object>> userDataPool = new HashMap<String, Map<String, Object>>();

	public Map<String, Map<String, Object>> getUserDataPool() {
		return userDataPool;
	}

	/**
	 * 获取当前用户订单信息
	 * 
	 * @param user
	 * @return
	 */
	private Map<String, Object> getLocalUserInfo(String user) {
		return userDataPool.get(user);
	}

	/**
	 * 获取当前用户订单列表
	 * 
	 * @param user
	 * @return
	 */
	private Map<String, OrderDto> getCurUserOrderList(String user) {
		Map<String, OrderDto> rst = null;
		if (getLocalUserInfo(user).get(TradeConfig.ORDER_LIST_KEY) == null) {
			rst = new HashMap<String, OrderDto>();
			getLocalUserInfo(user).put(TradeConfig.ORDER_LIST_KEY, rst);
		} else
			rst = (Map<String, OrderDto>) getLocalUserInfo(user).get(
					TradeConfig.ORDER_LIST_KEY);
		return rst;
	}

	public Map<String, OrderDto> getLocalUserSendOrder(String user) {
		Map<String, OrderDto> rst = null;
		if (getLocalUserInfo(user).get(TradeConfig.SEND_ORDER_KEY) == null) {
			rst = new HashMap<String, OrderDto>();
			getLocalUserInfo(user).put(TradeConfig.SEND_ORDER_KEY, rst);
		} else
			rst = (Map<String, OrderDto>) getLocalUserInfo(user).get(
					TradeConfig.SEND_ORDER_KEY);
		return rst;
	}

	private Map<String, OrderDto> getLocalUserCloseOrder(String user) {
		Map<String, OrderDto> rst = null;
		if (getLocalUserInfo(user).get(TradeConfig.CLOSE_ORDER_KEY) == null) {
			rst = new HashMap<String, OrderDto>();
			getLocalUserInfo(user).put(TradeConfig.CLOSE_ORDER_KEY, rst);
		} else
			rst = (Map<String, OrderDto>) getLocalUserInfo(user).get(
					TradeConfig.CLOSE_ORDER_KEY);
		return rst;
	}

	public String getSymbolInfo(String user) {
		// EURUSD,1.32250000,1.32270000;GBPUSD,1.61570000,1.61600000;USDJPY,85.90000000,85.92000000;USDCAD,0.99460000,0.99500000;
		return TradeUtils.getMTClientFileInfoByUser(user,
				TradeUtils.SYMBOL_INFO_FILE_PATH);
	}

	public String getUserOrderList(String user) {
		String rst = "";
		synchronized (this) {
			Map<String, OrderDto> localOrderList = getCurUserOrderList(user);
			String mtClientOrderList = TradeUtils.getMTClientFileInfoByUser(
					user, TradeUtils.ORDERS_FILE_PATH);
			// 如果mt端订单列表为空，则清空本地订单列表
			if (StringUtils.isBlank(mtClientOrderList)) {
				getCurUserOrderList(user).clear();
				return rst;
			}
			String[] mtClientOrderListArr = mtClientOrderList.split(";");
			// 如果mt端与本地订单列表长度不一致，表示mt端订单交易成功，则清空本地正在发送订单信息
			if (localOrderList.size() != mtClientOrderListArr.length) {
				getLocalUserSendOrder(user).clear();
			}
			// 清空本地订单信息，根据mt端重新设置本地订单信息
			localOrderList.clear();
			for (int i = 0; i < mtClientOrderListArr.length; i++) {
				String[] order = mtClientOrderListArr[i].split(",");
				String magic = order[0];
				String type = order[1];
				String volume = order[2];
				String symbol = fixSymbol(order[3]);
				String price = TradeUtils.fixPrice(symbol, order[4]);
				String bidPrice = TradeUtils.fixPrice(symbol, order[5]);
				String askPrice = TradeUtils.fixPrice(symbol, order[6]);
				type = getType(type);
				rst += magic + "," + type + "," + volume + "," + symbol + ","
						+ price + "," + bidPrice + "," + askPrice + ";";
				// 设置本地订单信息
				OrderDto dto = new OrderDto();
				dto.setMagic(magic);
				dto.setSymbol(symbol);
				dto.setType(type);
				localOrderList.put(magic, dto);
			}
		}
		return rst; // magic,type,volume,symbol,price,bidPrice,askPrice;
	}

	/**
	 * 修复货币名字
	 * 
	 * @param symbol
	 * @return
	 */
	private String fixSymbol(String symbol) {
		return symbol.replaceAll("\\.", "");
	}

	/**
	 * 根据是否对赌获取买卖类型
	 * 
	 * @param type
	 * @return
	 */
	private String getType(String type) {
		if (IS_DUIDU) {
			if (type.equals("1"))
				type = "0";
			else if (type.equals("0"))
				type = "1";
		}
		return type;
	}

	public boolean checkSendOrder(String user) {
		// 如果存在正在发送订单，则处理
		if (getLocalUserSendOrder(user).size() > 0) {
			// 获取mt端订单提交状态
			String mtOrderStatus = TradeUtils.getMTClientFileInfoByUser(user,
					TradeUtils.COMMAND_STATUS_FILE_PATH);
			if (StringUtils.isNotBlank(mtOrderStatus)) {
				TradeUtils.writeMTClientFileByUser(user,
						TradeUtils.COMMAND_STATUS_FILE_PATH, "");
				String[] data = mtOrderStatus.split(",");
				String magic = data[0];
				String symbol = fixSymbol(data[1]);
				String type = data[2];
				String status = data[3];
				OrderDto dto = getLocalUserSendOrder(user).get(magic);
				if (dto != null) {
					if (status.equals("true")) {
						// 提交成功，清空本地正在发送订单信息
						getLocalUserSendOrder(user).clear();
						return true;
					} else {
						// 提交失败
						return false;
					}
				}
			}
		}
		return true;
	}

	public boolean checkCloseOrder(String user) {
		// 如果本地存在关闭指令订单，则处理
		if (getLocalUserCloseOrder(user).size() > 0) {
			String mtCloseOrder = TradeUtils.getMTClientFileInfoByUser(user,
					TradeUtils.CLOSE_ORDER_FILE_PATH);
			if (StringUtils.isNotBlank(mtCloseOrder)) {
				String[] data = mtCloseOrder.split(",");
				String magic = data[0];
				String type = data[1];
				type = getType(type);
				String volumn = data[2];
				String symbol = fixSymbol(data[3]);
				String price = TradeUtils.fixPrice(symbol, data[4]);
				String bidPrice = TradeUtils.fixPrice(symbol, data[5]);
				String askPrice = TradeUtils.fixPrice(symbol, data[6]);
				String openTime = data[7].replace(";", "");

				String accountData = TradeUtils.getMTClientFileInfoByUser(user,
						TradeUtils.ACCOUNT_FILE_PATH);
				String account = accountData.split(",")[0];
				// String nowPrice = (type.equals("0")) ? askPrice : bidPrice;
				String nowPrice = (type.equals("1")) ? askPrice : bidPrice;
				int profit = Integer.parseInt(nowPrice.replace(".", ""))
						- Integer.parseInt(price.replace(".", ""));
				if (type.equals("1"))
					profit *= -1;
				double oldPrice = Double.parseDouble(accountData.split(",")[1]);
				double newProfit = Double.parseDouble(profit + "") / 10;
				double money = oldPrice + newProfit;
				TradeUtils.writeMTClientFileByUser(user,
						TradeUtils.ACCOUNT_FILE_PATH, user + "," + money);
				getLocalUserCloseOrder(user).clear();
				TradeUtils.writeMTClientFileByUser(user,
						TradeUtils.CLOSE_ORDER_FILE_PATH, "");
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String closeTime = sdf.format(new Date());
				String hData = magic + "," + type + "," + volumn + "," + symbol
						+ ",";
				hData += price + "," + nowPrice + "," + profit + "," + openTime
						+ "," + closeTime + ";";
				TradeUtils.writeFileAppendByLoginUser(user,
						TradeUtils.ORDER_HISTORY, hData);
				return true;
			}
		} else {
			return false;
		}
		return true;
	}

	public void clearLocalSendOrder(String user) {
		getLocalUserSendOrder(user).clear();
		getLocalUserCloseOrder(user).clear();
	}

	public void exOrderSend(String user, String symbol, String type,
			String magic) {
		String command = "";
		type = getType(type);
		if (type.equals("9")) {
			Map<String, OrderDto> localCloseOrder = getLocalUserCloseOrder(user);
			// 关闭订单
			OrderDto order = new OrderDto();
			order.setMagic(magic);
			order.setSymbol(symbol);
			order.setType(type);
			if (localCloseOrder.size() > 0) {
				// 如果第二次提交的货币跟上一次不同，则跳过
				OrderDto cOd = localCloseOrder.get(magic);
				if (cOd == null)
					return;
			}
			command = magic + "," + symbol + "," + type + ",true";
			localCloseOrder.put(order.getMagic(), order);
			getLocalUserSendOrder(user).put(order.getMagic(), order);
		} else {
			// 买卖订单
			OrderDto order = new OrderDto();
			order.setSymbol(symbol);
			order.setType(type);
			magic = RandomUtils.nextInt(1000000) + "";
			while (magic.length() < 7)
				magic += "0";
			command = magic + "," + symbol + "," + type + ",true";
			order.setMagic(magic);
			getLocalUserSendOrder(user).put(magic, order);
		}
		TradeUtils.writeMTClientFileByUser(user, TradeUtils.COMMAND_FILE_PATH,
				command);
	}
}
